<?php

/*
	Class: TodoItems

	About: Author
		Jaybill McCarthy

	About: License
		<http://communit.as/docs/license>

*/
class TodoItems extends Todo_Db_Table{

    protected $_name 	= 'todo_items';
    protected $_primary = 'id';

	/* Group: Has No Methods */
	
	function addForRole(
					$role_shortname,
					$assigned_by_username,  					
  					$task,
					$content_id = null,
					$contenttype_id = null,					
  					$url = null	
	){
		$users_table = new Users();
		$roles_table = new Roles();
		
		$users_db = $users_table->getByRoleId($roles_table->getIdByShortname($role_shortname));
		
		$users = array();
		foreach($users_db as $user){
			$users[] = $user['username'];
		}
		
		if(count($users) > 0){					
			return $this->add($users,$assigned_by_username,$task,$content_id,$contenttype_id,$url);
		}
	}
	
	function add($username,
					$assigned_by_username,  					
  					$task,
					$content_id = null,
					$contenttype_id = null,					
  					$url = null	
	){
		$users_table = new Users();
		if(!is_array($username)){
			$usernames = array($username);
		} else {
			$usernames = $username;
		}
		
		$data = array(  			
			'content_id'	=> $content_id,
  			'contenttype_id'=> $contenttype_id,
  			'assigned_by_username' => $assigned_by_username,  
  			'created_on' 	=> date(DB_DATETIME_FORMAT),   
  			'updated_on' 	=> date(DB_DATETIME_FORMAT),  
  			'task'			=> $task,
  			'url' 			=> $url,
		);
		
		$id = $this->insert($data);
		$items_users_table = new TodoItemsUsers();
		
		if(!is_null($id)){
			foreach($usernames as $tmp_username){
				$tmp_user = $users_table->fetchByUsername($tmp_username);
				
				if(!is_null($tmp_user)){
					$item_user_data = array(
						'item_id'	=> $id,
						'username' 	=> $tmp_username,
					);
					$items_users_table->insert($item_user_data);
				}
				
			}
			return $id;	
		}		
	}

	function delete($where){		
		$items = $this->fetchAll($this->select()->where($where));
		if (count($items) > 0){
			$items_users_table = new TodoItemsUsers();
			foreach($items as $item){
				$items_users_table->delete("item_id = ".$item->id);
			}
		
		}		
		return parent::delete($where);
	}
	
	
	function complete($id){		
		$data = array('completed' => 1);		
		$where = $this->getAdapter()->quoteInto("id = ?",$id);
		$this->update($data,$where);		
	}
	
}